//
//  StatusListModel.swift
//  SwiftWB
//
//  Created by 钟清 on 17/4/6.
//  Copyright © 2017年 Zhong Qing. All rights reserved.
//

import UIKit
import SVProgressHUD
import SDWebImage

class StatusListModel: NSObject {
    /* 保存所有微博数据的变量 */
    var statuses: [StatusViewModel]?

    // MARK: - 内部控制方法
    /* 下载数据 */
    func loadData(lastStatus: Bool, finished:(models:[StatusViewModel]?,error: NSError?) -> ()) {
        /* 1,刷新参数since_id和max_id处理 */
        var sinceId = statuses?.first?.status.idstr ?? "0"
        var maxId = "0"
        if lastStatus {
            sinceId = "0"
            maxId = statuses?.last?.status.idstr ?? "0"
        }
        /* 2, 网络请求 */
        NetworkTools.shareInstance.loadStatusesData(sinceId, max_id: maxId) { (array, error) in
            /* 安全校验 */
            if error != nil {
                finished(models: nil, error: error)
                return
            }
            /* 字典转模型数组 */
            var models = [StatusViewModel]()
            for dict in array! {
                let status = StatusesModel(dict: dict)
                let viewModel = StatusViewModel(status: status)
                models.append(viewModel)
            }
            /* 区分下载情况 */
            if sinceId != "0" { // 下拉刷新
                self.statuses = models + self.statuses!
            } else if maxId != "0"{ // 上拉刷新
                self.statuses = self.statuses! + models
            } else { // 初始加载
                self.statuses = models
            }
            /* 缓存配图 */
            self.cachesPictures(models, finished: finished)
        }
    }

    /* 缓存微博配图 */
    private func cachesPictures(viewModels: [StatusViewModel], finished: (models:[StatusViewModel]?,error: NSError?) -> ()) {
        let group = dispatch_group_create()
        
        for viewModel in viewModels {
            guard let pic_urls = viewModel.thumbnail_pic else {
                continue
            }
            for url in pic_urls {
                dispatch_group_enter(group)
                SDWebImageManager.sharedManager().downloadImageWithURL(url, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (image, error, _, _, _) in
                    // ZQLog("图片下载完成－子线程")
                    dispatch_group_leave(group)
                })
            }
        }
        dispatch_group_notify(group, dispatch_get_main_queue()) {
            // ZQLog("全部下载完成－主线程")
            finished(models: viewModels, error: nil)
        }
    }
    

}
